package br.org.ifrr.repository;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.org.ifrr.model.Inventario;
import br.org.ifrr.repository.filter.InventarioFilter;

public class Inventarios implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	@Inject
	private EntityManager manager;

	public Inventario guardar(Inventario inventario) {
		return manager.merge(inventario);
	}

	public Inventario porId(Long id) {
		return manager.find(Inventario.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<Inventario> filtrados(InventarioFilter filtro) {
		Session session = manager.unwrap(Session.class);
		Criteria criteria = session.createCriteria(Inventario.class);

		if (StringUtils.isNotBlank(filtro.getAno())) {
			criteria.add(Restrictions.ilike("inventario", filtro.getAno(),
					MatchMode.ANYWHERE));
		}

		return criteria.addOrder(Order.asc("inventario")).list();
	}

	public List<Inventario> porAnoInventaorio(String inventario) {
		
		return this.manager.createQuery("from Inventario where upper(inventario) like :inventario", Inventario.class)
				.setParameter("inventario", inventario.toUpperCase() + "%")
				.getResultList();
	}
	
	public Inventario porAno(String inventario) {
		try {
			return manager.createQuery("from Inventario where upper(inventario) = :inventario", Inventario.class)
					.setParameter("inventario", inventario.toUpperCase())
					.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
}
